const express = require("express");
const app = express();
const port = 9000;
const cors = require("cors");
const uuid = require("uuid");
const Response = require("./utils/Response");
app.use(
  cors({
    origin: "*",
  })
);
//配置multer 中间件 处理文件上传
const multer = require("multer");
const uploadTools = multer({
  storage: multer.diskStorage({
    // 该存储方案将会把文件直接存入磁盘
    destination: (req, file, callback) => {
      callback(null, "static");
    },
    filename: (req, file, callback) => {
      //通过file，获取原始文件名
      let name = file.originalname;
      //获取源文件的后缀，.jpg
      let ext = name.substr(name.lastIndexOf("."));
      //生成一个随机名
      let newName = uuid.v4() + ext;
      callback(null, newName);
    },
  }),
});
//配置静态资源托管文件夹 直接通过http://localhost:9000+文件命 直接访问
app.use(express.static("static"));
//文件上传接口 单张图片
app.post("/upload", uploadTools.single("file"), (req, resp) => {
  //multer中间件将会把文件存进req.file
  //uploadTools.array('file') 将会把file字段中传输的文件数据通过uploadTools接收并保存
  let url = "http://localhost:9000/" + req.file.filename;
  resp.send(Response.ok(url));
});
app.listen(port, () => {
  console.log("上传文件服务已经启动...");
});
